<script setup>
import { ref, watch, computed } from 'vue'
import Vcode from 'vue3-puzzle-vcode';
import { useStore } from 'vuex';
import { AddTable} from '../../../AxiosApi/api';
const store = useStore();
// 控制滑动验证码显示隐藏
const isshow = ref(false)
//  读取vuex中的isRegisterVisible
const isRegisterVisible = computed(() => store.getters.isRegisterVisible);
// 创建表单引用，用以调用表单实例                                                               
const formRef = ref(null)
// 倒计时相关
const countdown = ref(60) // 倒计时秒数
// 倒计时是否结束
const isCountingDown = ref(false)
// 注册按钮是否启用
const forbidden = ref(true)
// form表单的数据
const formItem = ref({
    username: '',//用户名
    email: '',//用户邮箱
    phone: '',//用户电话
    password: '',//用户密码
    confirmPassword: '',//确认密码    
    caches: '',
})
// 转存数据用以赋值给后端
const ListItem = ref({
    userName: '',//用户名
    email: '',//用户邮箱
    phone: '',//用户电话
    password:''//用户密码 
})
//接收后端返回的数据
const ReturnItem=ref({}) 


// 监听验证码输入框的变化
// 一个是要监听的数据源，另一个是当数据变化时的回调函数存储新值。
watch(() => formItem.value.captch, (newVal) => {
    forbidden.value = newVal === null || newVal === ''; // 如果验证码为空或null，则禁用注册按钮
})
// 再次确认密码规则 
const validatePassConfirm = (rule, value, callback) => {
    // rule 当前的验证规则对象。这个对象包含了当前验证规则的所有配置信息。
    // value当前输入框的值。这个值是你需要验证的实际数据
    // callback: 一个回调函数，用于通知验证结果。你必须调用这个函数来完成验证过程
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== formItem.value.password) {
        callback(new Error('两次输入密码不一致!'));
    } else {
        callback();
    }
}

// 表单校验规则
const rules = {
    // required：必填，message：提示信息，trigger：触发方式，blur：失去焦点，change：值改变时触发
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
    ],
    phone: [
        { required: true, message: "请输入手机号", trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入符合中国大陆的有效手机号码', trigger: 'blur' }
    ],
    password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        { min: 6, max: 15, message: "长度在 6 到 15 之间", trigger: "blur" },
        { pattern: /^(?=.*[a-z])(?=.*[A-Z]).{6,15}$/, message: "密码必须包含大小写字母且长度在 6 到 15 之间", trigger: "blur" }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validatePassConfirm, trigger: 'blur' }
    ]
}
// 点击注册时提交表单
const registerEvents = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            // 调用注册的方法
           ListItem.value= {
                userName:formItem.value.username,//用户名
                email: formItem.value.email,//用户邮箱
                phone: formItem.value.phone,//用户电话
                password: formItem.value.password,//用户密码 
            }
            RegisterMethod(ListItem.value);
            
        } else {
            alert("请按规定填写注册信息!");
        }
    });
}
// 注册信息的方法
const RegisterMethod = async () => {
    const response = await AddTable(ListItem.value)
    ReturnItem.value=response.data
    console.log(ReturnItem.value)
    if(ReturnItem.value==1){
        alert("注册成功！即将返回登录界面！");
        store.dispatch('ShowRegistration', false);
        store.dispatch('ShowLogin', true);
    }else{
    alert("注册失败！请检查信息！");
    }
}
// 处理滑动验证码成功
const handleCaptchaSuccess = (result) => {
    console.log('滑动验证码成功:', result);
    alert("滑动验证码成功！即将发送验证码!");
    isshow.value = !isshow.value//隐藏滑动验证码
    isCountingDown.value = true
    const timer = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--//自减
        } else {
            clearInterval(timer)//清除定时器
            isCountingDown.value = false
            countdown.value = 60 //重置倒计时
        }
    }, 1000)
    // 
};

// 处理滑动验证码失败
const handleCaptchaFail = (error) => {
    console.error('滑动验证码失败,请重试!:', error);
};
// 获取验证码方法
const onCaptchaCompleted = () => {
    // 进行表单验证
    formRef.value.validate((valid) => {
        if (valid) {
            isshow.value = !isshow.value
        } else {
            alert("请先按规定填写注册信息!");
        }
    });
}
const isButtonClicked = ref(false);
// 设置回到登录按钮的点击颜色
const BackToLogin = () => {
    isButtonClicked.value = true;
    setTimeout(() => {
        isButtonClicked.value = false; // 一段时间后恢复原状
        store.dispatch('ShowRegistration', false);
        store.dispatch('ShowLogin', true);
    }, 200)
    RegisterForm();

}

// 重置表单的方法
const RegisterForm = () => {
    formRef.value?.resetFields();
}

</script>
<template>
    <div class="register-div">
        <div class="register-div-2" v-show="isRegisterVisible">
            <el-form class="register-form" :model="formItem" :rules="rules" ref="formRef">
                <div class="register-title">注册</div>
                <!-- 用户名项 -->
                <el-form-item prop="username">
                    <el-input v-model="formItem.username" placeholder="请输入用户名" class="register-input"></el-input>
                </el-form-item>
                <!-- 用户邮箱项 -->
                <el-form-item prop="email">
                    <el-input v-model="formItem.email" placeholder="请输入邮箱" class="register-input"></el-input>
                </el-form-item>
                <!-- 手机号 -->
                <el-form-item prop="phone">
                    <el-input v-model="formItem.phone" placeholder="请输入手机号" class="register-input"></el-input>
                </el-form-item>
                <!-- 设置密码 -->
                <el-form-item prop="password">
                    <el-input v-model="formItem.password" placeholder="请输入密码" class="register-input"></el-input>
                </el-form-item>
                <!-- 确认密码 -->
                <el-form-item prop="confirmPassword">
                    <el-input v-model="formItem.confirmPassword" placeholder="请再次输入密码"
                        class="register-input"></el-input>
                </el-form-item>
                <div class="smsCaptchaType">
                    <el-input v-model="formItem.captch" placeholder="请输入手机验证码" class="register-inputYam" />
                    <el-button :disabled="isCountingDown" class="captcha-input" @click="onCaptchaCompleted">
                        {{ isCountingDown ? `${countdown}秒后重新发送` : '获取验证码' }}
                    </el-button>
                </div>
                <div class="register-btn-out">
                    <button :disabled="forbidden" :style="{ backgroundColor: forbidden ? 'grey' : '#008997' }"
                        @click="registerEvents" class="register-btn">注册</button>
                    <button :style="{ backgroundColor: isButtonClicked ? 'yellow' : '' }" @click="BackToLogin"
                        class="register-btn2">回到登录</button>
                </div>
            </el-form>
            <Vcode :show="isshow" @success="handleCaptchaSuccess" @fail="handleCaptchaFail" />
        </div>
    </div>
</template>
<style scoped>
.register-div {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.register-div-2 {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    background-color: #e0dddd;
}

.register-form {
    height: 85%;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    /* background-color: yellow; */
}

.register-btn2 {
    width: 140px;
    height: 50px;
    border-radius: 50px;
    color: white;
    background-color: #008997;
    font-size: 20px;
    font-weight: 500;
    border: none;
}

.register-btn {
    width: 140px;
    height: 50px;
    border-radius: 50px;
    color: white;
    background-color: grey;
    font-size: 20px;
    font-weight: 500;
    border: none;
}

.register-btn:hover {
    cursor: pointer;
}

.register-input {
    width: 300px;
    height: 40px;
}

.register-inputYam {
    width: 150px;
    height: 40px;
}

.register-title {
    font-size: 30px;
    width: 100%;
    text-align: center;
}

.register-input {
    width: 300px;
    height: 40px;
}

.register-inputYam {
    width: 150px;
    height: 40px;
}

.register-title {
    font-size: 30px;
    width: 100%;
    text-align: center;
}

.register-btn-out {
    width: 52%;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.smsCaptchaType {
    width: 52%;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.captcha-input {
    width: 140px;
}

.captcha-input:hover {
    cursor: pointer;
}

.send-sms-btn {
    width: 100px;
    font-size: 14px;
    margin-left: 30px;
}
</style>